<?php

namespace App\Jobs;

use App\Admin\Utils\Utils;
use App\Models\Contact;
use App\Models\MessageTemplate;
use App\Models\Record;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use PHPUnit\TextUI\XmlConfiguration\Constant;

class SendSMS implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $records;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($records)
    {
        $this->records = $records;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $utils = new Utils();
        $value = $this->records;

        $mobile = (Contact::find($value['contact_id']))['phone'];
        $content = (MessageTemplate::find($value['template_id']))['content'];
        if (isset($value['params']) && $value['params']) {
            $content = str_replace('【变量】', $value['params'], $content);
        }

        $result = $utils->sendSMS($mobile, $content);

        $value['status'] = $result['code'];
        $value['smsid'] = $result['smsid'];
        $value['msg'] = $result['msg'];

        Record::insert($value);
    }
}
